package cn.stylefeng.guns.modular.api.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.api.entity.Materiel;
import cn.stylefeng.guns.modular.api.entity.Product;
import cn.stylefeng.guns.modular.api.entity.Storage;
import cn.stylefeng.guns.modular.api.mapper.MaterielMapper;
import cn.stylefeng.guns.modular.api.mapper.ProductMapper;
import cn.stylefeng.guns.modular.api.mapper.StorageMapper;
import cn.stylefeng.guns.modular.api.model.enums.StorageStatusEnum;
import cn.stylefeng.guns.modular.api.model.params.MaterielParam;
import cn.stylefeng.guns.modular.api.model.params.StorageParam;
import cn.stylefeng.guns.modular.api.model.result.ERPValueItem;
import cn.stylefeng.guns.modular.api.model.result.MaterielResult;
import cn.stylefeng.guns.modular.api.model.result.StorageResult;
import cn.stylefeng.guns.modular.api.service.MaterielService;
import  cn.stylefeng.guns.modular.api.service.StorageService;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 出入库 服务实现类
 * </p>
 *
 * @author wusonghe
 * @since 2019-08-31
 */
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService {

    @Autowired
    private MaterielMapper materielMapper;

    @Autowired
    private ProductMapper productMapper;



    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void add(StorageParam param){

        //1.先调整原料

        try {
            if (StringUtils.isNotEmpty(param.getMaterielList())){
                List<ERPValueItem> erpValueItems = JSONObject.parseArray(param.getMaterielList(), ERPValueItem.class);
                for (ERPValueItem erpValueItem: erpValueItems) {
                    Materiel materiel = materielMapper.selectById(Integer.parseInt(erpValueItem.getValue()));
                    Integer subNumber =  Integer.parseInt(erpValueItem.getNumber());
                    Integer lastNumber = materiel.getNumber();
                    if (param.getStatus().equals(StorageStatusEnum.IN.getCode())) {
                        lastNumber = materiel.getNumber()+subNumber;
                    }else if (param.getStatus().equals(StorageStatusEnum.OUT.getCode())) {
                        lastNumber = materiel.getNumber()-subNumber;
                    }else if (param.getStatus().equals(StorageStatusEnum.MOVE.getCode())) {
                        lastNumber = materiel.getNumber()-subNumber;
                    }
                    materiel.setNumber(lastNumber);
                    if (materiel.getNumber()<0) {
                        throw new ServiceException(500, "出库/移库数量超出仓库容量");
                    }

                    //更换仓库
                    if (param.getStatus().equals(StorageStatusEnum.MOVE.getCode())) {
                        materiel.setPoodId(param.getPoodId());
                    }

                    materielMapper.updateById(materiel);
                }
            }


            //2.调整产品
            //只入库
            if (StringUtils.isNotEmpty(param.getProductList())) {
                List<ERPValueItem> productItems = JSONObject.parseArray(param.getProductList(), ERPValueItem.class);
                for (ERPValueItem erpValueItem: productItems) {
                    Product product = productMapper.selectById(Integer.parseInt(erpValueItem.getValue()));
                    Integer number_t =  Integer.parseInt(erpValueItem.getNumber());

                    //更新产品
                    Integer number_p = product.getNumber()-number_t;
                    if (number_p<0) {
                        throw new ServiceException(500,"产品数量不足");
                    }
                    product.setNumber(number_p);
                    productMapper.updateById(product);

                    //更新物料
                    MaterielParam materielParam = new MaterielParam();
                    materielParam.setTitle(erpValueItem.getName());
                    Materiel materiel = materielMapper.customDetail(materielParam);
                    if (materiel!=null){
                        Integer number = materiel.getNumber();
                        materiel.setNumber(number + number_t);
                        materielMapper.updateById(materiel);
                    }else {
                        Materiel productMateriel = new Materiel();
                        productMateriel.setTitle(product.getTitle());
                        productMateriel.setNumber(number_t);
                        productMateriel.setPoodId(param.getPoodId());
                        productMateriel.setSource(1); //自家
                        Long code = new Random().nextLong();
                        productMateriel.setMaterielCode(code.toString());
                        materielMapper.insert(productMateriel);
                    }
                }

            }

            //3.单个物料增加
            if (param.getMaterielId()!=null){
                Materiel materiel = materielMapper.selectById(param.getMaterielId());
                Integer subNumber = param.getMaterielNumber();
                subNumber = materiel.getNumber()+subNumber;
                materiel.setNumber(subNumber);
                materielMapper.updateById(materiel);
            }else {
                Materiel materiel = new Materiel();
                materiel.setNumber(param.getMaterielNumber());
                materiel.setMaterielCode(param.getMaterielCode());
                materiel.setUnit(param.getMaterielUnit());
                materiel.setTitle(param.getMaterielName());
                materiel.setType(param.getMaterielType());
                materiel.setRemark(param.getMaterielRemark());
                materielMapper.insert(materiel);

            }

            //更新明细
            Storage entity = getEntity(param);
            this.save(entity);

        }catch (Exception e) {
            throw new ServiceException(500,e.getMessage());
        }


    }

    @Override
    public void delete(StorageParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(StorageParam param){
        Storage oldEntity = getOldEntity(param);
        Storage newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public StorageResult findBySpec(StorageParam param){
        return null;
    }

    @Override
    public List<StorageResult> findListBySpec(StorageParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(StorageParam param){
        Page pageContext = getPageContext();
        if (pageContext.getSize()==0) {
            List datas =  this.baseMapper.customList(param);
            return LayuiPageFactory.createDataInfo(datas);
        }
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(StorageParam param){
        return param.getStorageId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Storage getOldEntity(StorageParam param) {
        return this.getById(getKey(param));
    }

    private Storage getEntity(StorageParam param) {
        Storage entity = new Storage();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
